// 用户相关的状态管理
import {request} from "@/utils/request";
import { createSlice } from "@reduxjs/toolkit";
import { loginAPI,getUserInfoAPI } from "@/apis/user";

const userStore = createSlice({
    name:'user',
    initialState:{
        token: localStorage.getItem('token') || '',
        userInfo:{}
    },
    reducers:{
        // 获取token
        setToken(state,action){
            state.token = action.payload
            localStorage.setItem('token',action.payload)
        },
        // 获取用户信息
        setUserInfo(state,action){
          state.userInfo =  action.payload
        },
        // 清除用户信息
        clearUserInfo(state){
          state.token = ''
          state.userInfo = {}
          localStorage.removeItem('token')
        }
    }
})

// 解构actions
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

// 异步登录方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}
// 异步获取用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { setToken, fetchLogin,fetchUserInfo ,clearUserInfo};

const userReducer = userStore.reducer

export default userReducer